package server

import (
	"config"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/gorilla/mux"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"html/template"
	"log"
	"math"
	"net/http"
	"sinffier/types"
	"strconv"
	"time"
)

type Response struct {
	Code      int
	Msg       string
	Count     int
	TotalPage float64
	List      []types.Mysql
}

func RunServer() {
	var dir string
	flag.StringVar(&dir, "dir", "static", "程序运行的目录. 默认当前目录")
	flag.Parse()
	//Mux
	r := mux.NewRouter().StrictSlash(true)
	//静态资源服务
	r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
	//API 服务
	r.HandleFunc("/", IndexHandler)
	r.HandleFunc("/mysql", MysqlLogsHandler)
	fmt.Println("API Server Running...")
	fmt.Printf("API Server Address: http://%s%s\n", config.API_ADDRESS, config.API_PORT)
	fmt.Println("-------------------------------")
	log.Fatal(http.ListenAndServe(config.API_PORT, r))
	//阻塞进程
	//select {}
}

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("static/dist/index.html")
	if err != nil {
		http.Error(w, "error 500:"+" "+err.Error(), http.StatusInternalServerError)
	}
	t.Execute(w, nil)
}

func MysqlLogsHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")

	query := r.URL.Query()

	var (
		page      int     = 10
		limit     int     = 10
		count     int     = 0
		TotalPage float64 = 0
	)

	if _, ok := query["rows"]; ok {
		intRow, err := strconv.Atoi(query["rows"][0])
		if err == nil {
			limit = intRow
		}
	}

	if _, ok := query["page"]; ok {
		intPage, err := strconv.Atoi(query["page"][0])
		if err == nil {
			page = intPage
		}
	}

	if page < 1 {
		errorResponse := []byte(`{"code":"402","msg":"Paramater error."}`)
		json.NewEncoder(w).Encode(errorResponse)
	}

	start := (page - 1) * limit

	//Connect MongoDB
	session, err := mgo.Dial(config.MONGO_HOST)
	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)
	collection := session.DB(config.DB_NAME).C("mysql") //collection
	result := []types.Mysql{}

	_, s_btm := query["b_tm"]
	_, s_etm := query["e_tm"]
	if s_btm && s_etm {

		//重要：获取时区
		loc, _ := time.LoadLocation("Local")
		//日期模板
		timeLayout := "2006-01-02 15:04:05"
		//开始时间
		beginTimeStr := fmt.Sprintf("%s 00:00:00", query["b_tm"][0])
		theBeginTime, _ := time.ParseInLocation(timeLayout, beginTimeStr, loc)
		startTime := theBeginTime.Unix()
		//结束时间
		endTimeStr := fmt.Sprintf("%s 23:59:59", query["e_tm"][0])
		theEndTime, _ := time.ParseInLocation(timeLayout, endTimeStr, loc)
		endTime := theEndTime.Unix()

		countRow, err := collection.Find(bson.M{"time": bson.M{"$gte": startTime, "$lt": endTime}}).Count()
		if err != nil {
			panic(err)
		}
		count = countRow
		//计算页数
		TotalPage = math.Ceil(float64(count) / float64(limit))
		collection.Find(bson.M{"time": bson.M{"$gte": startTime, "$lt": endTime}}).Sort("-time").Skip(start).Limit(limit).All(&result)
	} else {
		collection.Find(nil).Sort("-time").Skip(start).Limit(limit).All(&result)
		// 查找表总数
		countRow, err := collection.Count()
		if err != nil {
			panic(err)
		}
		count = countRow
		TotalPage = math.Ceil(float64(count) / float64(limit))
	}

	responseData := &Response{200, "success", count, TotalPage, result}

	json.NewEncoder(w).Encode(responseData)
}
